import { createRouter, createWebHistory } from "vue-router";
import Home from "@/components/homepage/Home.vue";
import { gsap } from "gsap";
import { showLoading, hideLoading } from "../components/Loading/useGsapLoading.js";
import { nextTick } from "vue";

// 路由配置
const routes = [
    { path: "/", name: "Home", component: Home },
    { path: "/detailed/:id/:merchantid", name: "Detailed", component: () => import('@/components/detailed/detailed.vue') },
    // 个人页面路由
    { path: "/user-profile", name: "UserProfile", component: () => import('@/components/personalcenter/Personal.vue') },
    { path: "/orders/:id/:name/:price/:quantity/:image/:selectedColor/:merchantid", name: "orders", component: () => import('@/components/detailed/Orders/orders.vue') },
    { path: "/payYes", name: "payYes", component: () => import('@/components/detailed/payYes/payYes.vue') },
];

// 创建 router 实例并传入路由配置
const router = createRouter({
    history: createWebHistory(),
    routes,
});

// 在路由切换后强制滚动到顶部
router.afterEach(() => {
    nextTick(() => {
        // 强制滚动到页面顶部
        document.documentElement.scrollTop = 0;
        document.body.scrollTop = 0;
        window.scrollTo(0, 0);
    });
});

// 在路由切换前显示加载动画（不再延迟）
router.beforeEach((to, from, next) => {
    const loading = document.querySelector(".loading-overlay");
    if (loading) {
        gsap.fromTo(
            loading,
            { opacity: 0 },
            { opacity: 1, duration: 1, ease: "power2.out", onStart: () => (loading.style.display = "flex") } // 动画持续1秒
        );
    }
    showLoading(loading);
    next();
});

// 在路由切换后隐藏加载动画并滚动到顶部
router.afterEach(() => {
    const loading = document.querySelector(".loading-overlay");
    if (loading) {
        gsap.to(loading, {
            opacity: 0,
            duration: 1,
            ease: "power2.in",
            onComplete: () => (loading.style.display = "none"),
        });
    }
    hideLoading(loading);

    // 在 DOM 更新后再滚动到顶部
    nextTick(() => {
        window.scrollTo(0, 0);
    });
});

export default router;
